package cn.stylefeng.guns.utils.weixin;

import cn.stylefeng.guns.modular.manager.entity.FlowOrder;
import cn.stylefeng.guns.modular.manager.entity.Miniprogram;
import cn.stylefeng.guns.modular.manager.entity.TemplateData;
import cn.stylefeng.guns.modular.manager.entity.WxTemplate;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class WxTemplateUtil {
    private static String APPID;

//    @Value("${wx.appId2}")
//    private String appId;
//
//    public WxTemplateUtil() {
//    }
//
//
//    @PostConstruct
//    public void init() {
//        APPID = this.appId;
//
//    }


    // 凭证获取（GET）

    public  String getToken() throws Exception{
        return  WeiXinUtil.getOfficeToken();
    }


    /**
     * 发送模板消息
     * appId 公众账号的唯一标识
     * appSecret 公众账号的密钥
     * openId 用户标识
     */
    public String send_template_message(FlowOrder flowOrder, String openId) {

//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long serverType=flowOrder.getOrderStatus();
//        Date date=flowOrder.getCreateTime();
//
//        String time=simpleDateFormat.format(date);
        String type="";
        if (serverType==0){
            type="已下单";
        }else if(serverType==1){
            type="已受理";
        }else if(serverType==5){
            type="已完成";
        }else if(serverType==6){
            type="已取消";
        }


        String access_token = null;
        try {
            access_token = this.getToken();
        } catch (Exception e) {
            e.printStackTrace();
//            log.error("获取公众号token失败"+e);
        }
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;


        WxTemplate wxTemplate = new WxTemplate();
        wxTemplate.setUrl("");
        wxTemplate.setTouser(openId);
        wxTemplate.setTopcolor("#000000");
//        wxTemplate.setTemplate_id("OH4rJIqyUmtyddS_AA7qrLsy_7YYWLpG0H3gO4j-Tas");
        wxTemplate.setTemplate_id("YOSbikcQa5T84OcewOQvrjxmcIxU3Sg5iYnczyjsN3M");
        Map<String, cn.stylefeng.guns.modular.manager.entity.TemplateData> m = new HashMap<>();

        Miniprogram miniprogram=new Miniprogram();
        miniprogram.setAppid(WeiXinConfig.sAppID);
        miniprogram.setPagepath("");
        wxTemplate.setMiniprogram(miniprogram);


        cn.stylefeng.guns.modular.manager.entity.TemplateData first = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
        first.setColor("#000000");
        first.setValue("您好，有新的佣金订单生成");
        m.put("first", first);
        cn.stylefeng.guns.modular.manager.entity.TemplateData keyword1 = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue(flowOrder.getOrderCode());
        m.put("keyword1", keyword1);
        cn.stylefeng.guns.modular.manager.entity.TemplateData keyword2 = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue(flowOrder.getName());
        m.put("keyword2", keyword2);
        cn.stylefeng.guns.modular.manager.entity.TemplateData keyword3 = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
        keyword3.setColor("#000000");
        keyword3.setValue(type);
        m.put("keyword3", keyword3);
//        cn.stylefeng.guns.modular.manager.entity.TemplateData keyword4 = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
//        keyword4.setColor("#000000");
//        keyword4.setValue(time);
//        m.put("keyword4", keyword4);
        TemplateData remark = new cn.stylefeng.guns.modular.manager.entity.TemplateData();
        remark.setColor("#000000");
        remark.setValue("点击详情，查看接单");
        m.put("remark", remark);
        wxTemplate.setData(m);

        String jsonString = JSONObject.toJSONString(wxTemplate).replace("day", "Day");
        JSONObject jsonObject = this.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        int result = 0;
        if (null != jsonObject) {
            if (0 != jsonObject.getInteger("errcode")) {
                result = jsonObject.getInteger("errcode");
//                log.error("错误 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
                return null;
            }else {
                //保存模板消息

                String msgid=jsonObject.getString("msgid");
                return msgid;
            }
        }
//        log.info("模板消息发送结果："+result);
        return null;
    }


    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());

            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            if (outputStr != null) {
                OutputStream outputStream = httpUrlConn.getOutputStream();

                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();

            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
//            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
//            log.error("https request error:{}", e);
        }
        return jsonObject;
    }







    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    /**
     * 将字符串进行sha1加密
     *
     * @param str 需要加密的字符串
     * @return 加密后的内容
     */
    public String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
